<template>
  <div class="mod-user">
    <el-form :model="query" :inline="true" @keyup.enter.native="getSubjectList()">
      <el-form-item>
        <el-select
          v-model="query.school_type"
          filterable
          clearable
          @change="changeSchoolTypeForQuery"
          placeholder="请选择所属阶段">
          <el-option
            v-for="item in schoolTypeList"
            :key="item.id"
            :label="item.value"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="query.grade_type"
          filterable
          clearable
          placeholder="请选择年级">
          <el-option
            v-for="item in gradeTypeListForQuery"
            :key="item.id"
            :label="item.value"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-input v-model="query.keyWord" placeholder="输入科目名称" type="text"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button v-if="hasPermission(['system:subject:list'])" type="success" icon="el-icon-search" @click="searchSubject()">查询</el-button>
        <el-button v-if="hasPermission(['system:subject:update'])" type="primary" @click="addSubject">新增</el-button>
        <el-button v-if="hasPermission(['system:subject:batchDelete'])" @click="batchDelete" type="danger">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="subjectList"
      border
      @select="checkData"
      @selection-change="handleSelectionChange"
      v-loading="loading"
      style="width: 100%;">

      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>

      <el-table-column
        prop="name"
        align="center"
        label="科目名称">
      </el-table-column>

      <el-table-column
        prop="use_flag"
        align="center"
        label="是否启用">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.use_flag" size="small">是</el-tag>
          <el-tag v-else size="small" type="danger">否</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="grade_type"
        align="center"
        label="所属阶段">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.school_type === 1" size="small">小学</el-tag>
          <el-tag v-else-if="scope.row.school_type === 2" size="small">初中</el-tag>
          <el-tag v-else="scope.row.school_type === 3" size="small">高中</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="grade_type"
        align="center"
        label="所属年级">
        <template slot-scope="scope">
            <el-tag size="small">{{scope.row.grade_type | getGradeName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="create_date"
        align="center"
        width="180"
        :formatter="formatterCreateDate"
        label="创建时间">
      </el-table-column>

      <el-table-column
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="warning"
            v-if="hasPermission(['system:subject:update'])"
            @click="updateSubject(scope.row)">修改</el-button>
          <el-button
            size="small"
            type="danger"
            v-if="hasPermission(['system:subject:deleteById'])"
            @click="deleteSubjectById(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="!form.id ? '新增科目' : '修改科目'"
      :close-on-click-modal="false"
      :visible.sync="showFlag">

      <el-form :model="form" :rules="rules" ref="form" @keyup.enter.native="saveOrUpdate()" label-width="80px">
        <el-form-item label="科目名称" prop="name">
          <el-input v-model="form.name" placeholder="科目名称"></el-input>
        </el-form-item>

        <el-form-item label="科目封面" prop="cover_img">
          <div v-if="form.cover_img">
            <ul class="el-upload-list el-upload-list--picture-card"
                style="display: inline-block;">
              <li class="el-upload-list__item is-success">
                <img :src="fileUrl + form.cover_img" alt=""
                     class="el-upload-list__item-thumbnail">
                <a class="el-upload-list__item-name"><i class="el-icon-document"></i></a>
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-check"></i></label> <i
                class="el-icon-close"></i>
                <i class="el-icon-close-tip">按 delete 键可删除</i>
                <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview"  @click="lookCoverImg"><i
                          class="el-icon-zoom-in"></i></span>
                          <span class="el-upload-list__item-delete" @click="deleteCoverImg"><i
                            class="el-icon-delete"></i></span>
                        </span>
                <el-dialog
                  :visible.sync="coverImgVisible"
                  custom-class="image-dialog"
                  append-to-body>
                  <img width="100%" :src="fileUrl + form.cover_img" alt="">
                </el-dialog>
              </li>
            </ul>
          </div>
          <div v-else>
            <el-upload
              :action="uploadAction"
              :headers="headers"
              :with-credentials="true"
              class="avatar-uploader"
              :on-success="uploadCoverImgSuccess"
              :before-upload="beforeUploadCoverImg"
              :show-file-list="false">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="所属阶段" placeholder="所属阶段" prop="school_type">
          <el-select
            :disabled="disabledUseFlag"
            @change="changeSchoolType"
            v-model="form.school_type"
            filterable
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in schoolTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属年级" placeholder="所属年级" prop="grade_type">
          <el-select
            :disabled="disabledUseFlag"
            v-model="form.grade_type"
            filterable
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in changeGradeTypeList"
              :key="item.id"
              :label="item.value"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用" size="mini">
          <el-radio-group  v-model="form.use_flag" :disabled="disabledUseFlag">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
          <span style="color: red; margin-left: 20px">(注: 当科目设置为启用状态时,阶段,年级,启用状态将无法再次修改)</span>
        </el-form-item>
      </el-form>

      <span slot="footer"  class="dialog-footer">
        <el-button @click="showFlag = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确定</el-button>
      </span>
    </el-dialog>

    <el-pagination
      background
      @size-change="sizeChangeHandler"
      @current-change="currentChangeHandler"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
</template>

<script>
  import { getUserId } from '@/utils'
  import { getSchoolTypeListApi, getGradeTypeListApi, getDictValueListByParentId } from '@/utils/system-dict-api'
  let thisPage = null
  export default {
    name: 'subject',
    data () {
      return {
        grade_type: '',
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        showFlag: false,
        loading: true,
        schoolTypeList: [],
        gradeTypeList: [],
        gradeTypeListForQuery: [],
        changeGradeTypeList: [],
        subjectList: [],
        form: {
          name: '',
          cover_img: '',
          use_flag: 0,
          user_id: 0,
          grade_type: '',
          school_type: ''
        },
        coverImgImageVisible: false,
        fileUrl: '',
        query: {
          school_type: '',
          grade_type: ''
        },
        headers: {
          token: localStorage.getItem('token')
        },
        disabledUseFlag: false,
        checkIds: [],
        coverImgVisible: false,
        uploadAction: this.$http.httpUrl('/upload/2'),
        rules: {
          name: [
            {required: true, message: '请输入科目名称', trigger: 'blur'}
          ],
          cover_img: [
            {required: true, message: '请上传科目封面图', trigger: 'blur'}
          ],
          school_type: [
            {required: true, message: '请选择所属阶段', trigger: 'blur'}
          ],
          grade_type: [
            {required: true, message: '请选择所属年级', trigger: 'blur'}
          ]
        }
      }
    },

    watch: {
      'form.use_flag' (val) {
        if (val === 1 && this.form.id) {
          this.disabledUseFlag = true
        } else {
          this.disabledUseFlag = false
        }
      }
    },

    beforeCreate () {
      thisPage = this
    },

    mounted () {
      let that = this
      that.form.user_id = getUserId()
      that.fileUrl = this.$http.getFileHost()
      that.getSubjectList()
      getGradeTypeListApi((data) => {
        that.gradeTypeList = data
        that.gradeTypeListForQuery = data
        that.changeGradeTypeList = data
      })
      getSchoolTypeListApi((data) => {
        that.schoolTypeList = data
      })
    },

    methods: {
      searchSubject () {
        this.currentPage = 1
        this.getSubjectList()
      },

      changeSchoolTypeForQuery (val) {
        let that = this
        let parentId = null
        that.schoolTypeList.forEach(item => {
          if (val === item.code) {
            parentId = item.id
          }
        })
        getDictValueListByParentId(parentId, 'grade_type', data => {
          that.gradeTypeListForQuery = data
        })
      },

      // 选中阶段
      changeSchoolType (val) {
        let that = this
        if (that.form.grade_type) {
          that.form.grade_type = ''
        }
        let parentId = null
        this.schoolTypeList.forEach(item => {
          if (item.code === val) {
            parentId = item.id
          }
        })
        getDictValueListByParentId(parentId, 'grade_type', data => {
          that.changeGradeTypeList = data
        })
      },

      clearFormData () {
        this.form = {
          name: '',
          cover_img: '',
          use_flag: 0,
          user_id: 0,
          grade_type: '',
          school_type: ''
        }
      },

      uploadCoverImgSuccess (res, file) {
        if (res.code === 1) {
          this.form.cover_img = res.url
        } else {
          this.$message.error(res.message)
        }
      },

      beforeUploadCoverImg (file) {
        let imgContentType = ['application/x-png', 'application/png', 'image/png', 'image/jpeg', 'image/gif']
        if (imgContentType.indexOf(file.type) === -1) {
          this.$message.error('图片格式错误, 只能上传JPG/PNG 格式,请重新上传')
          return false
        }
        let isLimit = file.size / 1024 / 1024 < 1
        if (!isLimit) {
          this.$message.error('上传图片大小不能超过 1MB!')
          return false
        }
        return true
      },

      lookCoverImg () {
        this.coverImgVisible = true
      },

      deleteCoverImg () {
        let that = this
        that.$confirm('确定移除该封面图吗？')
          .then(function () {
            that.form.cover_img = ''
          })
          .catch(function (error) {
            console.log(error)
          })
      },

      addSubject () {
        this.clearFormData()
        this.showFlag = true
      },

      handleSelectionChange (val) {
        this.checkIds = val
      },

      checkData (select) {
        console.log(select)
      },

      batchDelete () { // 批量删除
        let that = this
        that.$confirm('确定删除选中的科目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/subject/batchDelete'), {
            data: {
              ids: that.checkIds,
              sqlId: 'system.common.batchDeleteByIds',
              table: 'subject_info'
            }
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getSubjectList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },

      sizeChangeHandler (val) {
        this.pageSize = val
        this.currentPage = 1
        this.getSubjectList()
      },

      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      currentChangeHandler (val) {
        this.currentPage = val
        this.getSubjectList()
      },

      getSchoolTypeList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/dict'), {
          params: {
            'type': 'school_type'
          }
        }).then(function (response) {
          that.schoolTypeList = response.data.data.dataList
        })
      },

      getSubjectList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/subject/list'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            showFlag: true, // 是否展示所有科目(包括启用和未启用科目)
            schoolType: that.query.school_type,
            gradeType: that.query.grade_type,
            keyWord: that.query.keyWord
          }
        }).then(function (response) {
          that.loading = false
          that.subjectList = response.data.data.dataList
          that.totalCount = response.data.data.total
        })
      },

      saveOrUpdate () {
        let that = this
        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {
            that.axios.post(that.$http.httpUrl('/system/subject/saveOrUpdate'), that.form)
              .then(function (response) {
                that.showFlag = false // 必须在加载列表之前，否则会出现filters 中方法获取年级异常bug
                if (response.data.code === 1) {
                  that.$message({
                    type: 'success',
                    message: response.data.message
                  })

                  that.clearFormData()
                  that.getSubjectList()
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.message
                  })
                }
              }).catch(function (error) {
                console.log(error)
              })
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },

      // 注意 不能直接将item赋值给form
      updateSubject (item) {
        this.form = {
          id: item.id,
          name: item.name,
          use_flag: item.use_flag ? 1 : 0,
          user_id: item.user_id,
          cover_img: item.cover_img,
          grade_type: item.grade_type,
          school_type: item.school_type
        }
        delete (this.form.create_date)
        this.showFlag = true
      },

      deleteSubjectById (item) {
        if (item.use_flag) {
          this.$message.error('科目' + item.name + '已启用,无法删除')
          return
        }
        let that = this
        item.sqlId = 'system.common.deleteById'
        item.table = 'subject_info'
        that.$confirm('确定删除科目' + item.name + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/subject'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getSubjectList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      }
    },

    filters: {
      getGradeName (gradeType) {
        for (let i in thisPage.gradeTypeList) {
          if (thisPage.gradeTypeList[i].code === gradeType) {
            return thisPage.gradeTypeList[i].value
          }
        }
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
